using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Collections;
using System;

public class ImageLoader : MonoBehaviour
{
    private static ImageLoader _instance;

    // 重试配置
    [SerializeField] private int maxRetryCount = 3;  // 最大重试次数
    [SerializeField] private float retryDelay = 1f;  // 重试间隔时间（秒）

    public static ImageLoader Instance
    {
        get
        {
            if (_instance == null)
            {
                // 创建一个新的 GameObject 并添加 ImageLoader 组件
                GameObject obj = new GameObject("ImageLoader");
                _instance = obj.AddComponent<ImageLoader>();
            }
            return _instance;
        }
    }

    private void Awake()
    {
        // 确保单例模式
        if (_instance == null)
        {
            _instance = this;
            DontDestroyOnLoad(gameObject); // 在场景切换时不销毁
        }
        else
        {
            Destroy(gameObject); // 如果已经存在实例，则销毁当前对象
        }
    }

    // 调用此方法来加载远程图像
    public void LoadImageFromUrl(Image imageComponent, string url, Action callback = null)
    {
        StartCoroutine(DownloadImageWithRetry(imageComponent, url, callback));
    }

    private IEnumerator DownloadImageWithRetry(Image imageComponent, string url, Action callback = null)
    {
        int currentRetryCount = 0;
        bool downloadSuccess = false;

        while (!downloadSuccess && currentRetryCount < maxRetryCount)
        {
            if (currentRetryCount > 0)
            {
                Debug.Log($"正在重试下载图片 ({currentRetryCount}/{maxRetryCount}): {url}");
                yield return new WaitForSeconds(retryDelay);
            }

            using (UnityWebRequest webRequest = UnityWebRequestTexture.GetTexture(url))
            {
                // 发送请求并等待响应
                yield return webRequest.SendWebRequest();

                if (webRequest.result == UnityWebRequest.Result.Success)
                {
                    downloadSuccess = true;
                    // Debug.Log("下载图像成功: " + url);
                    // 获取下载的纹理
                    Texture2D texture = DownloadHandlerTexture.GetContent(webRequest);
                    // 将纹理转换为Sprite
                    Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                    // 设置Image组件的sprite
                    imageComponent.gameObject.SetActive(true);
                    imageComponent.sprite = sprite;
                    callback?.Invoke();
                }
                else
                {
                    currentRetryCount++;
                    if (currentRetryCount >= maxRetryCount)
                    {
                        Debug.LogError($"图片下载失败，已达到最大重试次数 ({maxRetryCount}): {url}\n错误信息: {webRequest.error}");
                    }
                    else
                    {
                        Debug.LogWarning($"图片下载失败，准备重试 ({currentRetryCount}/{maxRetryCount}): {url}\n错误信息: {webRequest.error}");
                    }
                }
            }
        }
    }
}